<template>

  <!--<div class="background">-->
  <!--  <el-image :src="require('@/assets/images/backGround/backGround_login.jpg')"/>-->
  <!--</div>-->
  <!--<div name="introduce">软件登录页</div>-->

  <el-row type="flex" class="row-bg" justify="center">
    <el-col :xl="5" :lg="6">
        <h2 class="login-title">欢迎访问 link with health</h2>
        <h2 class="login-title">在线问诊系统</h2>
        <el-image :src="require('@/assets/images/backGround/backGround_login.jpg')"
                  style="width: 100%; height: 100%"/>
    </el-col>
    <el-col :span="1"><el-divider direction="vertical"></el-divider></el-col>
    <el-col :xl="7" :lg="8">
      <el-row name="authWay" v-if="!isLoginByPhone" justify="center">
        <!--表单验证 账号名登录-->
        <el-form :model="loginForm" status-icon :rules="rules"
                 ref="loginForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="账号" prop="account">
            <el-input type="text" v-model="loginForm.account"
                      autocomplete="off" placeholder="请输入账号名或id"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="loginForm.password"
                      autocomplete="off" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="verificationCode">
            <el-input v-model="loginForm.verificationCode"
                      placeholder="请输入验证码"
                      @keyup.enter.native="submitForm('loginForm')">
              <el-image slot="append"
                        class="img-code"
                        @click="getImage"
                        :src="imageCode.img"></el-image>
            </el-input>

          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('loginForm')">提交</el-button>
            <el-button @click="">注册</el-button>
          </el-form-item>
          <el-form-item>
            <el-button @click="changeLoginWay('loginForm')" class="switch">切换登陆方式</el-button>
          </el-form-item>
        </el-form>
      </el-row>

      <el-row name="authWay" v-if="isLoginByPhone" justify="center">
        <!-- 表单登录 电话登录-->
        <el-form :model="phoneLoginForm" status-icon :rules="rules" ref="phoneLoginForm"
                 label-width="100px" class="demo-ruleForm">
          <el-form-item label="手机" prop="phone">
            <el-input type="text" v-model="phoneLoginForm.phone" autocomplete="off" placeholder="请输入手机号码">
            </el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="smsCode">
            <el-input v-model="phoneLoginForm.smsCode"
                      placeholder="请输入接收的验证码"
                      @keyup.enter.native= "submitForm('phoneLoginForm')">
              <el-button slot="append" :disabled="smsButton.btnStatus"
                         @click="sendSms()">{{smsButton.btnText}}</el-button>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('phoneLoginForm')">
              提交</el-button>
            <el-button @click="">注册</el-button>
          </el-form-item>
          <el-form-item>
            <el-button @click="changeLoginWay('phoneLoginForm')"
                       class="switch">切换登陆方式</el-button>
          </el-form-item>
        </el-form>
      </el-row>

    </el-col>

  </el-row>


</template>

<script>
export default {
  name: "Login",
  data() {
    let checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('年龄不能为空'));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入数字值'));
        } else {
          if (value < 18) {
            callback(new Error('必须年满18岁'));
          } else {
            callback();
          }
        }
      }, 1000);
    };
    let checkPhone = (rule, value, callback) => {
      let pattern = /^(13[0-9]|14[5|7]|15[0-9]|1[6|8-9][0-9])\d{8}$/;
      if (value === '') {
        console.log(value);
        callback(new Error('电话不能为空'));
      }
      if (!pattern.test(value)) {
        console.log(value);
        console.log(pattern.test(value));
        callback(new Error('请输入正确手机号码'));
      }
      callback();
    };
    let validateAccount = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入账号'))
      }
      callback();
    };
    let validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      }
      callback();
    };
    let checkVerificationCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入验证码'));
      }
      // else if (value !== this.imageCode.code)
      //   callback(new Error('验证码不一致'));
      callback();
    };
    let checkSmsCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入验证码'));
      }
      callback();
    };

    return {
      isLoginByPhone: false,

      imageCode: {
        img: '',
        code: ''
      },

      smsButton: {
        limitTime: 61,
        btnText: '发送短信',
        btnStatus: false
      },

      loginForm: {
        account: '',
        password: '',
        verificationCode: '',
        token: ''
      },
      phoneLoginForm: {
        phone: '',
        smsCode: '',
        token: ''
      },
      rules: {
        password: [
          {required: true, validator: validatePassword, trigger: 'blur' }
        ],
        account: [
          { required: true,validator: validateAccount, trigger: 'blur'}
        ],
        verificationCode: [
          { required: true,validator: checkVerificationCode, trigger: 'blur'}
        ],
        phone: [
          { required: true, validator: checkPhone, trigger: 'blur' }
        ],
        smsCode: [
          { required: true, validator: checkSmsCode, trigger: 'blur'}
        ]
      },
    };
  },
  methods: {
    myAxios(api,jsonData) {
      const self = this;
      return new Promise((resolve, reject)=>{
        self.$axios({
          method: 'post',
          url: api,
          data: jsonData
        }).then((res)=>{
          resolve(res.data);
        }).catch(err=>{
          console.log("this ->" + err)
          console.log("this ->" +  err.date)
          reject('error');
        })
      })
    },

    submitForm(formName) {
      let url = 'api/login/verify/verifyByPassword';
      let loginBody = this.loginForm;


      if(formName === 'phoneLoginForm'){
        url = 'api/login/verify/verifyByPhone';
        loginBody = this.phoneLoginForm;
      }

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.post(url, loginBody)
              .then(res=>{
                if(res.data.code !== 200){
                  return false
                }

                const token = res.data.data.token;
                this.$store.commit("SET_TOKEN",token);
                this.$router.push("/index")
              }).catch((e)=>{console.log(e)})
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    changeLoginWay(formName) {
      const con = this;
      con.isLoginByPhone = !con.isLoginByPhone;
      try{
        this.$refs[formName].resetFields();
      } catch (e) {

      }
    },
    async getImage(){
      let json = {'userId':this.loginForm.account};
      let rsp = await this
          .myAxios('api/login/imageCode',json)

        let data = rsp.data;
        console.log("this->"+ data);
        let format = "data:image/png;base64,";
        this.imageCode.code=data.code;
        this.imageCode.img=format+data.img;
        this.loginForm.token = data.code;

    },
    smsTimer(val) {
      const that = this;
      let userPhone = that.phoneLoginForm.phone;
      let limitTime = Number(val);
      const timer = setInterval(function() {
        if (limitTime > 1) {
          limitTime--;
          that.smsButton.btnStatus = true;
          let display = limitTime > 9 ? limitTime : '0'+ limitTime;
          that.smsButton.btnText = `${display}s后重新获取`;
          let expire = new Date().getTime() + limitTime * 1000;
          //console.log('set: '+expire);
          that.$cookieStore.setCookie(userPhone
              , expire, 60)
        } else {
          that.$cookieStore.delCookie(userPhone)
          clearInterval(timer)
          that.smsButton.btnText = '获取验证码';
          that.smsButton.btnStatus = false;
        }
      }, 1000)
    },
    sendSms(){

      const that = this;
      let userPhone = that.phoneLoginForm.phone;
      let isValid = false;

      that.$refs['phoneLoginForm'].validateField(
        'phone',(error) => {
          isValid = error !== '';
        })
      if(isValid){
        return;
      }
      const expire = that.$cookieStore.getCookie(userPhone);
      const timeWait = (expire - new Date().getTime()) / 1000 | 0;

      console.log('get: '+expire);
      console.log('timeWait: '+timeWait);
      if(timeWait !== undefined && timeWait > 0){
        that.smsTimer(timeWait);
      } else {


        that.$cookieStore.setCookie(userPhone
            , new Date() + 61*1000, 60);
        that.smsTimer(61);
      }
      //发送请求
      that.myAxios('api/login/verify/sendSms')
          .then(res=>{
            that.phoneLoginForm.token = res.data.data.token;
          }).catch(err=>{
            console.log(err);
      })

    }

  },
  created(){
    this.getImage();
  }
}
</script>

<style scoped>
  .background {


    position:fixed;
    background: url("../../assets/images/backGround/backGround_login.jpg");
  }

  .el-row{
    background: #f7f9fb;
    height: 100%;
    display: flex;
    align-items: center;
  }
  .el-divider {
    height: 200px;
  }
  .login-title{
    text-align: center;
  }
  .img-code{
    width: 100px;
    height: 40px;
  }
  .el-form-item{
    width: 380px;
  }

</style>